/*
 * @Author: yanbinbin
 * @Date: 2021-04-21 17:51:17
 * @LastEditTime: 2021-04-22 14:53:34
 * @LastEditors: Please set LastEditors
 * @Description: InheritedWidget跨层数据共享,数据的流动方式父到子
 * @FilePath: \inherited_widget\lib\count_container.dart
 */

import 'package:flutter/material.dart';

class CounterPage extends StatefulWidget {
  CounterPage({Key? key}) : super(key: key);

  @override
  _CounterPageState createState() => _CounterPageState();
}

class _CounterPageState extends State<CounterPage> {
  int count = 0;

  void _incrementCounter() => setState(() {
        count++;
      });

  @override
  Widget build(BuildContext context) {
    return CountContainer(
        //increment: _incrementCounter,
        model: this,
        increment: _incrementCounter,
        child: Counter());
  }
}

class CountContainer extends InheritedWidget {
  //提供Of方法方便子组件在组件树中找到它
  static CountContainer of(BuildContext context) =>
      context.dependOnInheritedWidgetOfExactType<CountContainer>()
          as CountContainer;
  //直接使用_CounterPageState中的State获取数据
  final _CounterPageState model;

  final Function() increment;

  CountContainer({
    Key? key,
    required this.model,
    required this.increment,
    required Widget child,
  }) : super(key: key, child: child);

// 判断是否需要更新
// 该回调决定当data发生变化时，是否通知子树中依赖data的Widget
  @override
  bool updateShouldNotify(CountContainer oldWidget) {
    //如果返回true，则子树中依赖(build函数中有调用)本widget
    //的子widget的`state.didChangeDependencies`会被调用
    return model != oldWidget.model;
  }
}

class Counter extends StatefulWidget {
  Counter({Key? key}) : super(key: key);

  @override
  _CounterState createState() => _CounterState();
}

class _CounterState extends State<Counter> {
  @override
  void didChangeDependencies() {
    //父或祖先widget中的InheritedWidget改变(updateShouldNotify返回true)时会被调用。
    //如果build中没有依赖InheritedWidget，则此回调不会被调用。
    print("Dependencies change");
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    CountContainer state = CountContainer.of(context);
    return Scaffold(
      appBar: AppBar(
        title: Text("InheritedWidget demo"),
      ),
      body: Text(
        'You have pushed the button this many times: ${state.model.count}',
      ),
      floatingActionButton: FloatingActionButton(onPressed: state.increment),
    );
  }
}

// class Counter extends StatelessWidget {
//   @override
//   Widget build(BuildContext context) {
//     print('Counter====>BuildContext');
//     //  获取InheritedWidget节点
//     CountContainer state = CountContainer.of(context);

//     return Scaffold(
//       appBar: AppBar(
//         title: Text("InheritedWidget demo"),
//       ),
//       body: Text(
//         'You have pushed the button this many times: ${state.model.count}',
//       ),
//       floatingActionButton: FloatingActionButton(onPressed: state.increment),
//     );
//   }
// }
